﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

using Mvc.XForms.Utilities;

namespace Mvc.XForms.Controls.Settings {
	public class PartialSettings<TContext, T> {
		private IContainerControl<TContext> parent;
		private Expression<Func<TContext, T>> bind;
		private object model;
		private ViewDataDictionary viewData;

		public PartialSettings(IContainerControl<TContext> parent, Expression<Func<TContext, T>> bind) {
			this.parent = parent;
			this.bind = bind;
		}

		public PartialSettings<TContext, T> Model(object model) {
			this.model = model;
			return this;
		}

		public PartialSettings<TContext, T> ViewData(ViewDataDictionary viewData) {
			this.viewData = viewData;
			return this;
		}

		public void Render() {
			var partialViewName = bind.Body.ExtractMember();
			Render(partialViewName);
		}

		public void Render(string partialViewName) {
			var htmlHelper = parent.XForm.HtmlHelper;
			if (htmlHelper == null)
				throw new InvalidOperationException("HtmlHelper not set");

			var context = new XFormContext<TContext, T>(parent, bind);

			if (viewData == null)
				viewData = new ViewDataDictionary(htmlHelper.ViewData);

			// Find this a bit hacky, but its easier than creating
			// a whole new view structure
			viewData.Add("XFormContext", context);

			htmlHelper.RenderPartial(partialViewName, model, viewData);
		}
	}
}